// pages/detail/index.js
var time= require("../../utils/util.js");
const db=wx.cloud.database();
const _ = db.command
var app=getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    reply:'',
    show: false,
    loading: true,
    delete:false,
    rpValue:"发表想法",//回复框中的文字
    id:'',
    userid:'',
    current_item:'{}',
    current_assure_item:'{}',
    current_item:'{}',
    current_id:'',//目前点击的帖子或评论的id
    current_openid:'',//目前点击的帖子或评论的人的openid
    data_list:[],
    haveimge:false,
    comment_type:0,
    iscollected:false
  },
  onDelete()
  {
    let that = this;
    var id=this.data.current_id
    var topicID=this.data.id
    var type=topicID==id
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (res) {
       if (res.confirm) {
        wx.showLoading({
          title: '删除中',
          icon:'loading',
          mask:true
        })
        wx.cloud.callFunction({
          name:"delete",
          data:{
            id:id,
            topicID:topicID,
            type:type
          }
        }).then(res=>{

          console.log(res);
          if(type==false){
              that.setData({
                          loading: true,
                          data_list: []
                        });
                        setTimeout(async function(){
                          await that.getData();
                          that.setData({
                            loading: false
                          })
                        },1000)

          }
          else{
            setTimeout(function(){
              wx.reLaunch({
                url: '../forum/index',
              })
            },1000)
           
          }
           wx.hideLoading()
                wx.showToast({
                  title: '删除成功',
                })
          })
      }
       else if (res.cancel) {
         console.log('点击取消了');
         return false;    
        }
      }
    })
    this.onClose()
  },
  showPopup(e) {//展示弹出层
    var userid = getApp()
    var oid=e.currentTarget.dataset
    if(oid.comment_info)
    {//点击的是评论中的3个点
      
      this.setData({ 
        current_item:oid.comment_info,
        current_id:oid.comment_info._id,
        current_openid:oid.comment_info._openid
      });
      if(oid.comment_info._openid==userid.globalData.openid)
    {//如果是楼主,显示删除
      this.setData({ 
        delete:true
      });
    }
    else{//不是楼主显示举报
      this.setData({ 
        delete:false,
      });
    }
    }
    else{//点击的是帖子的3个点
      this.setData({ 
        current_item:'{}',//回复楼主，设置为空，未选择评论
        current_id:this.data.id,
        current_openid:this.data._openid
      });
    }
    this.setData({ 
      show: true ,
      userid:userid.globalData.openid,
    });

  },

  onClose() {//关闭弹出层
    this.setData({  
      show: false, 
      current_item:'{}' 
     }); 
  },

  onReply(e){
    if(this.data.current_item==='{}')
    {
      this.setData({
        rpValue:'回复楼主'
      })
    }
    else{
      this.setData({
        rpValue:'回复：'+this.data.current_item.uName
      })
    }
    this.setData({  
      current_assure_item:this.data.current_item,
      show: false, 
      current_item:'{}' 
    }); 
  },


  inputReply:function(e){
    var reply=e.detail.value
    this.setData({
      reply:reply
    })
    console.log(reply);
  },

  pulishReply:function(e){

    var that=this
    if(this.data.reply.length==0){
      wx.showToast({
        icon:'none',
        title: '请回复内容',
      })
    }
    else{
      console.log(this.data.current_assure_item==='{}');
      
      wx.showLoading({
        title: '发布中',
        icon:'loading',
        mask:true
      })
      var data = {
        topicID:that.data.id,
        rContent:that.data.reply,
        rTime: Date.parse(new Date())/1000,
        rLikes:0,
        uName:app.globalData.uName,
        head_pic:app.globalData.head_pic,
        rReplyContent:this.data.current_assure_item=="{}"? "":this.data.current_assure_item.rContent,
        rReplyUserName:this.data.current_assure_item=="{}"? "":this.data.current_assure_item.uName,
      }
  
      wx.cloud.callFunction({
        name: 'contentCheck',
        data: {
          msg: that.data.reply
        },
        success(res) {
          if (res.result.errCode == 87014) {
            console.log(res.errCode)
            wx.showToast({
              icon:'error',
              title: '文字违规',
            })
          }
          else{
            db.collection("reply").add({
              data:data,
              success:res=>{
                wx.hideLoading()
                wx.showToast({
                  title: '发布成功',
                })
                that.getData(10,0,false)
                that.setData({
                  reply:'',
                  current_assure_item:"{}"
                })
              },
              fail:e=>{
                wx.showToast({
                  title: '发布错误',
                })
                console.log(e)
              },

              })
                  
              wx.cloud.callFunction({
                name:"addLikesOrReply",
                data:{
                  id:that.data.id,
                  type:1//1是回帖，0是赞
                }
              })
            }  
            }
        })
  
    }
    
  },
  addReplyLike:function(e){
    var r_id=e.currentTarget.dataset.index
    var cache = wx.getStorageSync('cache_key');
    // 获取当前文章是否被点赞的缓存
    var currentCache = cache[this.data.currentId];

    currentCache[r_id]=true

    // 更新cache中的对应的1个的缓存值，使其等于当前取反的缓存值
    cache[this.data.currentId] = currentCache;
    // 重新设置缓存
    wx.setStorageSync('cache_key',cache);
 
    this.setData({
     likes_list: currentCache,
     
    })
    wx.showToast({
      title: 'loading',
      icon:'loading',
    })
    wx.cloud.callFunction({
      name:"addLikesOrReply",
      data:{
        id:r_id,
        type:0//1是回帖，0是赞
      }
    }).then(res=>{
      console.log(res);
      this.getData(10,0,false)
    })

  },
  addCollect:function(e){
    var id=this.data.id
    wx.showToast({
      title: 'loading',
      icon:'loading',
    })
    wx.cloud.callFunction({
      name:'addCollect',
      data:{
        id:id
      }
    }).then(res=>{
      this.setData({
        iscollected:true
      })
      console.log(res);
    })

   var cache=wx.getStorageSync('userInfo')
   var collect_list=cache.collect
   collect_list.push(id)
   cache.collect=collect_list
    // // 重新设置缓存
    wx.setStorageSync('userInfo',cache);

  
  },
  previewImg: function (e) {
    console.log(this.data);
    console.log(e);
    //获取当前图片的下标
    var index = 0;
    //所有图片
    var imgs = [this.data.imgPaths];
    console.log(index,imgs);
    wx.previewImage({
    //当前显示图片
    current: imgs[index],
    //所有图片
    urls: imgs
    })
   },
  getData(num=10,page=0,isconcat=true){
    wx.cloud.callFunction({
      name:"post",
      data:{
        num:num,
        page:page,
        topicID:this.data.id
      }
    }).then(res=>{
 
      var list=res.result.data
      for(var i=0;i<list.length;i++){
        var item_time=time.formatTime(list[i].rTime)
        list[i].time=item_time
      }
      if(isconcat==true){
        var oldData=this.data.data_list
        var newData=oldData.concat(list)
      }
      else{
        var newData=list
      }
      this.setData({
        data_list:newData
      })
    })
    const that = this;
      setTimeout(()=>{
        that.setData({
          loading:false
        })
      },300)
    console.log(this.data.data_list);
  },
  async goToChartRoom(e){
    let uID = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;
    let MyID = wx.getStorageSync('userInfo')._id;
    let res = await db.collection('user').doc(uID).get();
    let uTime = res.data.timestamp;
    let mTime = wx.getStorageSync('userInfo').timestamp;
    let gid = uTime+mTime;
   let id = uID + "" + MyID;
    wx.navigateTo({
      url: `/pages/im/room/room?id=${id}&name=${name?name:this.data.uName}&gid=${gid}`,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    
    //从数据库获取数据
    db.collection("topic").where({
      _id:options.id.replace(/\s+/g,"")
    }).get()
    .then(res=>{
      var topicInfo=res.data[0]
      this.setData({
        id:topicInfo._id,
        title:topicInfo.title,
        imgPaths:topicInfo.imgPaths,
        tTime:time.formatTime(topicInfo.tTime),
        likes:topicInfo.topicLikes,
        _openid:topicInfo._openid,
        content:topicInfo.tContent,
        head_pic:topicInfo.head_pic,
        uName:topicInfo.uName,
      })
      if(this.data.imgPaths.length!=0)
      {
        this.setData({
          haveimge:true
        })
      }
      this.getData()
   
    })
      // 获取接收到的id值
      var getId = options.id
      // 让接收到的id值传递到data:{}里面
      this.setData({
      currentId: getId
      });
      // 读取所有的文章列表点赞缓存状态
      var cache = wx.getStorageSync('cache_key');
      // 如果缓存状态存在
      if (cache) {
      // 拿到所有缓存状态中的1个
      var currentCache = cache[getId];
      if(currentCache==null){
        cache[getId] = {};
      wx.setStorageSync('cache_key',cache);
      }
      this.setData({
        likes_list: currentCache
      })
      } else {
      // 如果所有的缓存状态都不存在 就让不存在的缓存存在
      var cache = {};
      cache[getId] = {};
      // 把设置的当前文章点赞放在整体的缓存中
      wx.setStorageSync('cache_key',cache);
      }
      
      wx.getStorage({
        key:'userInfo',
        success:function(res){
          var collect_list=res.data.collect
          var isid=getId.replace(/\s+/g,"")
          if(collect_list.indexOf(isid)>-1){
            that.setData({
              iscollected:true
            })
          }
        }
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // this.setData({
    //   loading: false,
    // });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var page=this.data.data_list.length
    this.getData(7,page)


  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  }
})